package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;
	@Autowired
	private ItemDescMapper itemDescMapper;

	@Override
	public EasyUITable findItemByPage(Integer page, Integer rows) {
		//1.1通过分页对象  将page  rows进行参数的封装
		IPage iPage = new Page(page, rows);
		//2.pageHelper  添加某些参数  经过分页查询之后返回pageHelper对象(包含了分页的其他参数)
		//...
		QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("updated");
		//通过iPage对象封装其他的分页数据
		iPage = itemMapper.selectPage(iPage,queryWrapper);
		long total = iPage.getTotal();
		List<Item> itemList = iPage.getRecords();
		return new EasyUITable(total, itemList);
	}


	@Transactional  //标记方式使用事务控制
	@Override
	public void saveItem(Item item,ItemDesc itemDesc) {
		item.setStatus(1);  //设定启动状态
//				.setCreated(new Date()).setUpdated(item.getCreated());
		itemMapper.insert(item);
		itemDesc.setItemId(item.getId());
		itemDescMapper.insert(itemDesc);

	}

	@Override
	@Transactional
	public void updateItem(Item item,ItemDesc itemDesc) {
		itemMapper.updateById(item);
		itemDescMapper.updateById(itemDesc.setItemId(item.getId()));
	}

	//方式1: sql delete from tb_item where xxxx
	@Override
	@Transactional
	public void deleteItem(Long[] ids) {
		itemMapper.deleteIds(ids);
		List<Long> idList = Arrays.asList(ids);
		itemDescMapper.deleteBatchIds(idList);
	}

	@Override
	public void updateStatus(Integer status, Long[] ids) {
		//参数1:实体对象  将要修改的数据封装
		//参数2:条件构造器  动态拼接where条件
		Item item = new Item();
		item.setStatus(status);
		UpdateWrapper updateWrapper = new UpdateWrapper();
//		List<Long> idList = Arrays.asList(ids);
		updateWrapper.in("id", ids);
		itemMapper.update(item,updateWrapper);
	}

	@Override
	public ItemDesc findItemDescById(Long id) {
		return itemDescMapper.selectById(id);
	}


//	@Override
//	public EasyUITable findItemByPage(Integer page, Integer rows) {
//		//1.获取记录总数
//		long total = itemMapper.selectCount(null);
//		//2.分页查询
//		int startIndex = (page-1)*rows;
//		List<Item> pageList = itemMapper.findItemByPge(startIndex,rows);
//
//		return new EasyUITable(total,pageList);
//	}
}
